<script setup>
  import {
    ref
  } from "vue";
  import {
    fabric
  } from "fabric";
  import {
    nextTick,
    onMounted
  } from "vue";
  import defbg from "@/assets/img/defbg.jpg";

  import z1 from "@/assets/img/z1.png";
  import z2 from "@/assets/img/z2.png";
  import z3 from "@/assets/img/z3.png";
  import z4 from "@/assets/img/z4.png";
  import z5 from "@/assets/img/z5.png";
  import z6 from "@/assets/img/z6.png";
  import z7 from "@/assets/img/z7.png";
  import z8 from "@/assets/img/z8.png";
  import z9 from "@/assets/img/z9.png";
  import z10 from "@/assets/img/z10.png";
  import z11 from "@/assets/img/z11.png";
  import z12 from "@/assets/img/z12.png";
  import z13 from "@/assets/img/z13.png";
  import z14 from "@/assets/img/z14.png";
  import z15 from "@/assets/img/z15.png";
  import z16 from "@/assets/img/z16.png";
  import z17 from "@/assets/img/z17.png";
  import z18 from "@/assets/img/z18.png";
  import z19 from "@/assets/img/z19.png";
  import z20 from "@/assets/img/z20.png";
  import z21 from "@/assets/img/z21.png";
  import z22 from "@/assets/img/z22.png";
  import z23 from "@/assets/img/z23.png";
  import z24 from "@/assets/img/z24.png";
  import z25 from "@/assets/img/z25.png";
  import p1 from "@/assets/img/p1.png";
  import p2 from "@/assets/img/p2.png";
  import p3 from "@/assets/img/p3.png";
  import p4 from "@/assets/img/p4.png";
  import p5 from "@/assets/img/p5.png";

  let wh = window.innerHeight;
  let ww = window.innerWidth;
  let main = null;
  const boderIndex = ref(0)
  let pGroup = [p1, p2, p3, p4, p5];
  let zGroup = [z1, z2, z3, z4, z5, z6, z7, z8, z9, z10, z11, z12, z13, z14, z15, z16, z17, z18, z19, z20, z21, z22,
    z23, z24, z25
  ];

  let pIndex = 0;
  let zIndex = 0;

  let pImg = null;
  let zImg = null;

  let pAndz = false;

  let group = null;

  window.addEventListener("resize", () => {
    wh = window.innerHeight;
    ww = window.innerWidth;
    if (main == null) {
      main = new fabric.Canvas("main", {
        width: ww,
        height: wh,
        backgroundColor: "black",
      });
    } else {
      main.setWidth(ww);
      main.setHeight(wh);
      main.renderAll();
      main.calcOffset();
    }
  });

  onMounted(() => {
    nextTick(() => {
      console.log(-4 % 3);
      main = new fabric.Canvas("main", {
        width: ww,
        height: wh,
        backgroundColor: "black",
      });

      fabric.Image.fromURL(defbg, (oImg) => {
        oImg.scale(0.5); // 缩放
        // main.add(oImg); // 将图片加入到画布
        main.setBackgroundImage(
          oImg,
          main.renderAll.bind(main), // 刷新画布
          {
            //保证背景图1:1铺满容器
            scaleX: main.width / oImg.width, //计算出图片要拉伸的宽度
            scaleY: main.height / oImg.height, //计算出图片要拉伸的高度
          }
        );
      });

      fabric.Image.fromURL(
        pGroup[0],
        (opImg) => {
          opImg.scale(0.25);
          console.log(opImg, 'opImgopImgopImg');
          pImg = opImg;

          main.add(pImg);
        }, {
          left: 180,
          top: 267
        }
      );

      fabric.Image.fromURL(
        zGroup[0],
        (ozImg) => {
          ozImg.scale(0.25);
          zImg = ozImg;

          main.add(zImg);
        }, {
          left: 105,
          top: 45
        }
      );
    });

    // console.log(pImg);
    // // 创建组
    // group = new fabric.Group([pImg, zImg], {
    //   objectCaching: false, // 不缓存！！！
    // });
    // // 将分组添加到canvas里
    // main.add(group);

    // let rect = new fabric.Rect({
    //   left: 100,
    //   top: 100,
    //   fill: "red",
    //   width: 30,
    //   height: 30,
    // });

    // main.add(rect);
  });

  const beforeUpload = (file) => {
    // 图片格式限制为 jpeg、png
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      this.$message.error("请选择jpg/png图片");
      return false;
    }
    // 图片大小限制为 10M以内
    const isLt10M = file.size / 1024 / 1024 <= 10;
    F
    if (!isLt10M) {
      this.$message.error("图片大小不能超过10MB，请重新上传");
      return false;
    }
    return isJpgOrPng && isLt10M;
  };

  const httpRequest = (file) => {
    const reader = new FileReader();
    reader.readAsDataURL(file.file);
    reader.addEventListener("loadend", function(e) {
      fabric.Image.fromURL(e.target.result, (oImg) => {
        oImg.scale(0.5); // 缩放
        main.add(oImg); // 将图片加入到画布
        main.setBackgroundImage(
          oImg,
          main.renderAll.bind(main), // 刷新画布
          {
            //保证背景图1:1铺满容器
            scaleX: main.width / oImg.width, //计算出图片要拉伸的宽度
            scaleY: main.height / oImg.height, //计算出图片要拉伸的高度
          }
        );
      });

      //  const image = new Image()
      //  image.src = e.target.result
      //  image.onload = async function () {
      //    if (image.width !== 1920 || image.height !== 268) {
      //      _this.$message.error('需要符合要求尺寸的图片！')
      //      return false
      //    } else {
      //      formData.append('file', file.file)
      //      const { code, data } = await uploadArticleFile(formData)
      //      if (code === 200) {
      //        _this.$message.success('上传成功！')
      //        _this.$emit('uploadImg', data.url)
      //      } else {
      //        _this.$message.error('上传失败！请重新上传')
      //      }
      //    }
      //  }
    });
  };

  const httpRequest2 = (file) => {
    console.log(main.getActiveObject());
    const reader = new FileReader();
    reader.readAsDataURL(file.file);
    reader.addEventListener("loadend", function(e) {
      fabric.Image.fromURL(e.target.result, (oImg) => {
        oImg.scale(0.05); // 缩放
        main.add(oImg); // 将图片加入到画布
      });
    });
  };

  const httpRequest3 = (file) => {
    const reader = new FileReader();
    reader.readAsDataURL(file.file);
    reader.addEventListener("loadend", function(e) {
      fabric.Image.fromURL(e.target.result, (oImg) => {
        oImg.scale(0.05); // 缩放
        main.add(oImg); // 将图片加入到画布
      });
    });
  };

  const handleChangez = () => {
    pAndz = true;
    if (zImg) {
      zIndex++;
      zImg.setSrc(zGroup[Math.abs(zIndex % 3)], () => {
        main.renderAll();
      });
    }
  };

  const handleChangep = () => {
    pAndz = false;
    if (pImg) {
      pIndex++;
      pImg.setSrc(pGroup[Math.abs(pIndex % 5)], () => {
        main.renderAll();
      });
    }
  };

  // import { onMounted, nextTick } from "vue";

  // export default {
  //   data() {
  //     return {
  //       main: null,
  //       uploaderUrl: "",
  //     };
  //   },
  //   name: "Polygon",
  //   setup() {
  //     onMounted(() => {
  //       nextTick(() => {
  //         let that = this
  //         let height = window.innerHeight
  //         let width = window.innerWidth

  //         this.main = new fabric.Canvas("main", {
  //           width,
  //           height,
  //           backgroundColor: "black",
  //         });

  //         // let dbimg = new fabric.Image(defImg)

  //         // this.main.mainsetBackgroundImage(
  //         //   dbimg,
  //         //   canvas.renderAll.bind(that.main)
  //         // )
  //       });
  //     });
  //   },
  //   methods:{
  //     uploadImg(e) {
  //       let file = e.target.files[0];
  //       //异步获取文件
  //       let reader = new FileReader();
  //       reader.onload = (e) => {
  //         this.uploaderUrl = e.target.result;
  //       };
  //       reader.readAsDataURL(file);
  //     },
  //     draw() {
  //       console.log(this.canvas);
  //       if (this.canvas) {
  //         console.log("canvas!!!!");
  //         this.canvas.dispose(); //释放
  //       }
  //       this.canvas = new fabric.Canvas("main");
  //       let uploadImg = document.createElement("img");
  //       uploadImg.src = this.uploaderUrl;

  //       let img = new fabric.Image(uploadImg, {
  //         left: 0,
  //         top: 0,
  //       });
  //       this.canvas.add(img).setActiveObject(img);

  //       // let rect = new fabric.Rect({
  //       //   left:100,
  //       //   top:100,
  //       //   fill:'red',
  //       //   width:30,
  //       //   height:30
  //       // })

  //       // this.canvas.add(rect)

  //       // 设置边框和缩放隐藏
  //       // this.canvas.item(0).hasControls = this.canvas.item(0).hasBorders = false;
  //       // 双指手势取消移动
  //       // this.canvas.on("touch:gesture", () => {
  //       //   // getActiveObject 返回当前活动对象
  //       //   const activeObj = this.canvas.getActiveObject();
  //       //   if (activeObj) {
  //       //     activeObj.set({
  //       //       lockMovementX: true,
  //       //       lockMovementY: true,
  //       //     });
  //       //   }
  //       // });
  //       // this.canvas.on("mouse:up", () => {
  //       //   const activeObj = this.canvas.getActiveObject();
  //       //   if (activeObj) {
  //       //     activeObj.set({
  //       //       lockMovementX: false,
  //       //       lockMovementY: false,
  //       //     });
  //       //   }
  //       // });
  //     },
  //   }
  // };

  let box = document.querySelector('body') // 监听对象
  let startTime = '' // 触摸开始时间
  let startDistanceX = '' // 触摸开始X轴位置
  let startDistanceY = '' // 触摸开始Y轴位置
  let endTime = '' // 触摸结束时间
  let endDistanceX = '' // 触摸结束X轴位置
  let endDistanceY = '' // 触摸结束Y轴位置
  let moveTime = '' // 触摸时间
  let moveDistanceX = '' // 触摸移动X轴距离
  let moveDistanceY = '' // 触摸移动Y轴距离
  box.addEventListener("touchstart", (e) => {
    startTime = new Date().getTime()
    startDistanceX = e.touches[0].screenX
    startDistanceY = e.touches[0].screenY
  })
  box.addEventListener("touchend", (e) => {
    endTime = new Date().getTime()
    endDistanceX = e.changedTouches[0].screenX
    endDistanceY = e.changedTouches[0].screenY
    moveTime = endTime - startTime
    moveDistanceX = startDistanceX - endDistanceX
    moveDistanceY = startDistanceY - endDistanceY
    console.log(moveDistanceX, moveDistanceY)
    // 判断滑动距离超过40 且 时间小于500毫秒
    if ((Math.abs(moveDistanceX) > 40 || Math.abs(moveDistanceY) > 40) && moveTime < 500) {
      // 判断X轴移动的距离是否大于Y轴移动的距离
      if (Math.abs(moveDistanceX) > Math.abs(moveDistanceY)) {
        // 左右
        // console.log(moveDistanceX > 0 ? '左' : '右')
        // if (moveDistanceX > 0) {
        //   handleChange(1)
        // } else {
        //   handleChange(-1)
        // }
      } else {
        // 上下
        console.log(moveDistanceY > 0 ? '上' : '下')
      }
    }
  })

  const handleChange = (value) => {
    if (pAndz) {
      if (zImg) {
        zIndex = zIndex + value;
        zImg.setSrc(zGroup[Math.abs(zIndex % 3)], () => {
          main.renderAll();
        });
      }
    } else {
      if (pImg) {
        pIndex = pIndex + value;
        pImg.setSrc(pGroup[Math.abs(pIndex % 5)], () => {
          main.renderAll();
        });
      }
    }
  };
  // 点击左侧绿植
  const leftPlantChange = (item, index) => {
    boderIndex.value = index
    pAndz = true;
    if (zImg) {
      zIndex++;
      zImg.setSrc(zGroup[index], () => {
        main.renderAll();
      });
    } else {
      fabric.Image.fromURL(
        zGroup[index],
        (ozImg) => {
          ozImg.scale(0.25);
          zImg = ozImg;

          main.add(zImg);
        }, {
          left: 105,
          top: 45
        }
      );
      fabric.Image.fromURL(
        pGroup[0],
        (opImg) => {
          opImg.scale(0.25);
          pImg = opImg;
          main.add(pImg);
        }, {
          left: 180,
          top: 267
        },
      )
    }

  }
  // 点击右侧盆栽
  const rightPlantChange = (item, index) => {
    console.log(pImg, 'pImg');
    pAndz = false;
    if (pImg) {
      pIndex++;
      pImg.setSrc(pGroup[index], () => {
        main.renderAll();
      });
    } else {
      fabric.Image.fromURL(
        zGroup[0],
        (ozImg) => {
          ozImg.scale(0.25);
          zImg = ozImg;
      
          main.add(zImg);
        }, {
          left: 105,
          top: 45
        }
      );
      fabric.Image.fromURL(
        pGroup[index],
        (opImg) => {
          opImg.scale(0.25);
          pImg = opImg;
          main.add(pImg);
        }, {
          left: 180,
          top: 267
        },
      )
    }
  }
  const saveImg = () => {
    var canvasData = document.getElementById("main");
    var a = document.createElement("a");
    a.href = canvasData.toDataURL();;
    a.download = "drcQrcode";
    a.click();
  }
  let aGroup = null
  let objPositionLeft = ''
  let objPositionTop = ''
  const synthesis = () => {
    let aaa = new fabric.Group([pImg, zImg], {
      objectCaching: true,
    });
    zImg = null
    pImg = null
    main.add(aaa);
    // if (aGroup == null) {
    //   // 创建组
    //   if (objPositionLeft == '') {
    //     aGroup = new fabric.Group([pImg, zImg], {
    //       objectCaching: true,
    //     });
    //     objPositionLeft = aGroup.left
    //     objPositionTop = aGroup.top
    //     zImg = null
    //     pImg = null
    //   } else {
    //     aGroup = new fabric.Group([zImg, pImg], {
    //       objectCaching: true,
    //       top: objPositionTop,
    //       left: objPositionLeft
    //     });
    //   }
    //   main.add(aGroup);
    // }


    // let rect = new fabric.Rect({
    //   left: 100,
    //   top: 100,
    //   fill: "red",
    //   width: 30,
    //   height: 30,
    // });

    // main.add(rect);
  }
  // 分开图层

  const splitGroup = () => {
    main.remove(aGroup)
    aGroup = null
  }
  const del = () => {
    var el = main.getActiveObject();
    if (el) {
      main.remove(el);
      // pImg = null
    } else {

    }
  }

  const paste = (_clipboard) => {
    // clone again, so you can do multiple copies.
    let canvas = main;
    _clipboard.clone(function(clonedObj) {
      canvas.discardActiveObject();
      clonedObj.set({
        left: clonedObj.left + 20,
        top: clonedObj.top + 20,
        evented: true,
      });
      if (clonedObj.type === 'activeSelection') {
        // active selection needs a reference to the canvas.
        clonedObj.canvas = canvas;
        clonedObj.forEachObject(function(obj) {
          canvas.add(obj);
        });
        // this should solve the unselectability
        clonedObj.setCoords();
      } else {
        canvas.add(clonedObj);
      }
      _clipboard.top += 20;
      _clipboard.left += 20;
      canvas.setActiveObject(clonedObj);
      // canvas.requestRenderAll();
    });
  }
  const copy = () => {
    var _self = this;
    main.getActiveObject().clone(function(cloned) {
      // let _clipboard = cloned;
      paste(cloned);

    })
  }
</script>

<template>

  <!-- <a-button>Add</a-button> -->
  <!-- <input
      type="file"
      name=""
      id=""
      @change="uploadImg"
    />
  <div style="position: fixed;top: 0;left: 0;">
    <img :src="uploaderUrl" @load="draw" alt="" style="display:none"/>
  </div> -->
  <!-- 上边工具栏 start -->
  <div class="t_tool">
    <div class="t_tool_text" @click="copy">复制</div>
    <div class="t_tool_text">常规</div>
    <div class="t_tool_text">材质</div>
    <div class="t_tool_text">盆形</div>
    <div class="t_tool_text">风格</div>
    <div class="t_tool_text">删除</div>
  </div>
  <!-- 上边工具栏 end -->
  <div class="c_tool">
    <div class="c_tool_item">
      <img src="@/assets/img/tu1.png" alt="">
      <span>圆形</span>
    </div>
    <div class="c_tool_item">
      <img src="@/assets/img/tu2.png" alt="">
      <span>方形</span>
    </div>
    <div class="c_tool_item">
      <img src="@/assets/img/tu3.png" alt="">
      <span>椭圆形</span>
    </div>
    <div class="c_tool_item">
      <img src="@/assets/img/tu4.png" alt="">
      <span>三角形</span>
    </div>
  </div>
  <div class="lightBulb">
    <img src="@/assets/img/dengpao.png" alt="">
  </div>
  <div class="collection">
    <img src="@/assets/img/sc.png" alt="">
  </div>
  <!-- <a-upload class="upLoadBg" :action="'#'" :show-upload-list="false" :customRequest="httpRequest"
    :before-upload="beforeUpload">
    <a-button>
      <upload-outlined></upload-outlined>
      上传背景
    </a-button>
  </a-upload> -->

  <!-- <a-button class="upLoadBg2" @click="handleChangez">切换植物</a-button>

  <a-button class="upLoadBg3" @click="handleChangep">切换盆景</a-button> -->
  <!-- 左侧植物 start -->
  <div class="leftPlant">
    <div v-for="(item,index) in zGroup" @click="leftPlantChange(item, index)" :key="index"
      :class="boderIndex == index ?'bordera': 'borderb'">
      <img :src="item" alt="">
    </div>
  </div>
  <!-- 左侧植物 end -->
  <!-- 右侧盆栽 start -->
  <div class="rightPlant">
    <img v-for="(item,index) in pGroup" :key="index" :src="item" alt="" @click="rightPlantChange(item, index)">
  </div>
  <!-- 右侧盆栽 end -->
  <!-- 底部栏目 -->
  <div class="t_bottom">
    <div class="t_b_add" @click="saveImg">
      <img src="@/assets/img/add.png" alt="">
      <div>保存图片</div>
    </div>
    <div class="t_b_time" @click="splitGroup">
      <img src="@/assets/img/time.png" alt="">
      <div>送达天数</div>
    </div>
    <div class="t_b_complete" @click="synthesis">
      完成改款
    </div>
  </div>
  <!-- <a-upload
    class="upLoadBg2"
    :action="'#'"
    :show-upload-list="false"
    :customRequest="httpRequest2"
    :before-upload="beforeUpload"
  >
    <a-button>
      <upload-outlined></upload-outlined>
      上传盆景
    </a-button>
  </a-upload> -->

  <!-- <a-upload
    class="upLoadBg3"
    :action="'#'"
    :show-upload-list="false"
    :customRequest="httpRequest3"
    :before-upload="beforeUpload"
  >
    <a-button>
      <upload-outlined></upload-outlined>
      上传植物
    </a-button>
  </a-upload> -->

  <canvas id="main"></canvas>

  <!-- <div>
    <a href="https://vitejs.dev" target="_blank">
      <img src="/vite.svg" class="logo" alt="Vite logo" />
    </a>
    <a href="https://vuejs.org/" target="_blank">
      <img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
    </a>
  </div>
  <HelloWorld msg="Vite + Vue" /> -->
</template>
<style src="@/assets/index.css">

</style>